"""
Case Type   : GUC_ErrorLog
Case Name   : 日志的级别为log以下，修改参数debug_print_plan的值为on
Create At   : 2022/06/02
Owner       : liu-tong-8848
Description :
    1.logging_collector设置为on,log_min_messages设置为debug3，log_directory设置新的路径
    2.修改参数debug_print_plan的值为on
    3.重启数据库生成日志信息，查看日志内容
    4.设置log_min_messages设置为error
    5.重启数据库生成日志信息，执行sql查询语句，查看日志
    6.恢复参数
    7.清理残留日志
Expect      :
    1.设置成功
    2.修改成功
    3.重启数据库成功，日志中打印查询执行结果
    4.设置成功
    5.重启数据库成功，执行sql查询语句成功，日志中未打印查询执行结果
    6.恢复成功
    7.清理成功
History     :
"""
import os
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant


class ErrorLog(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.primary_node = Node('PrimaryDbUser')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.primary_root = Node('PrimaryRoot')
        self.common = Common()
        self.constant = Constant()
        self.tb_name = 't_guc_errorlog_case0090'
        self.dir_new = os.path.join(macro.PG_LOG_PATH, 'pg_errorlog_case0090')
        self.collector = 'logging_collector'
        self.collector_default = self.common.show_param(self.collector)
        self.log_min_msg = 'log_min_messages'
        self.log_min_msg_default = self.common.show_param(self.log_min_msg)
        self.log_dir = 'log_directory'
        self.log_dir_default = self.common.show_param(self.log_dir)
        self.debug_plan = 'debug_print_plan'
        self.debug_plan_default = self.common.show_param(self.debug_plan)

    def test_error_log(self):
        text = '-----step1:前置条件:logging_collector设置为on,log_min_messages' \
               '设置为debug3，log_directory设置新的路径;expect:设置成功-----'
        self.logger.info(text)
        if 'on' != self.collector_default:
            result = self.primary_sh.execute_gsguc(
                'set', self.constant.GSGUC_SUCCESS_MSG,
                f'{self.collector}=on')
            self.assertTrue(result, '执行失败' + text)
            restart_res = self.primary_sh.restart_db_cluster()
            self.assertTrue(restart_res, '执行失败' + text)
        show_msg = self.common.show_param(self.collector)
        self.assertEquals(show_msg, 'on', '执行失败' + text)

        if 'debug3' != self.log_min_msg_default:
            result = self.primary_sh.execute_gsguc(
                'reload', self.constant.GSGUC_SUCCESS_MSG,
                f'{self.log_min_msg}=debug3')
            self.assertTrue(result, '执行失败' + text)
        show_msg = self.common.show_param(self.log_min_msg)
        self.assertEquals(show_msg, 'debug3', '执行失败' + text)

        if self.dir_new != self.log_dir_default:
            result = self.primary_sh.execute_gsguc(
                'reload', self.constant.GSGUC_SUCCESS_MSG,
                f'{self.log_dir}=\'{self.dir_new}\'')
            self.assertTrue(result, '执行失败' + text)
        show_msg = self.common.show_param(self.log_dir)
        self.assertEquals(show_msg, self.dir_new, '执行失败' + text)

        text = '-----step2:修改参数debug_print_plan的值为on;' \
               'expect:修改成功-----'
        self.logger.info(text)
        if 'on' != self.debug_plan_default:
            result = self.primary_sh.execute_gsguc(
                'reload', self.constant.GSGUC_SUCCESS_MSG,
                f'{self.debug_plan}=on')
            self.assertTrue(result, '执行失败' + text)
        show_msg = self.common.show_param(self.log_dir)
        self.assertEquals(show_msg, self.dir_new, '执行失败' + text)

        text = '-----step3:重启数据库生成日志信息，查看日志内容;' \
               'expect:重启数据库成功，日志中打印查询执行结果-----'
        self.logger.info(text)
        rm_cmd = f'''cd {self.dir_new} && rm -f * && ls -l'''
        self.logger.info(rm_cmd)
        rm_msg = self.primary_node.sh(rm_cmd).result()
        self.logger.info(rm_msg)
        self.assertEquals('total 0', rm_msg, '执行失败:' + text)
        self.logger.info('-------重启数据库生成日志信息-------')
        restart_res = self.primary_sh.restart_db_cluster()
        self.assertTrue(restart_res, '执行失败' + text)
        self.logger.info('-------查看日志文件内容-------')
        shell_cmd = f'''ls -t {self.dir_new} '''
        self.logger.info(shell_cmd)
        logfile = os.path.join(self.dir_new,
                               self.primary_root.sh(shell_cmd).result())
        self.logger.info(logfile)
        cat_cmd = f"cat {logfile} | grep 'LOG:  plan'"
        self.logger.info(cat_cmd)
        cat_msg = self.primary_node.sh(cat_cmd).result()
        self.logger.info(cat_msg)
        self.assertIn('LOG:  plan', cat_msg, '执行失败:' + text)

        text = '-----step4:设置log_min_messages设置为error;expect:设置成功-----'
        self.logger.info(text)
        result = self.primary_sh.execute_gsguc('reload',
                                               self.constant.GSGUC_SUCCESS_MSG,
                                               f'{self.log_min_msg}=error')
        self.assertTrue(result, '执行失败' + text)
        text = '-----step5:重启数据库生成日志信息，执行sql查询语句，查看日志;' \
               'expect:重启数据库成功，执行sql查询语句成功，日志中未打印查询执行结果-----'
        self.logger.info(text)
        rm_msg = self.primary_node.sh(rm_cmd).result()
        self.logger.info(rm_msg)
        self.assertEquals('total 0', rm_msg, '执行失败:' + text)
        restart_res = self.primary_sh.restart_db_cluster()
        self.assertTrue(restart_res, '执行失败' + text)
        self.logger.info('-------重启数据库生成日志信息-------')
        show_msg = self.common.show_param(self.log_min_msg)
        self.assertEquals(show_msg, 'error', '执行失败' + text)
        self.logger.info('-------查看日志文件内容-------')
        shell_cmd = f'''ls -t {self.dir_new} '''
        self.logger.info(shell_cmd)
        logfile = os.path.join(self.dir_new,
                               self.primary_root.sh(shell_cmd).result())
        self.logger.info(logfile)
        cat_cmd = f"cat {logfile} | grep 'LOG:  plan'"
        self.logger.info(cat_cmd)
        cat_msg = self.primary_node.sh(cat_cmd).result()
        self.logger.info(cat_msg)
        self.assertNotIn('LOG:  plan', cat_msg, '执行失败:' + text)

    def tearDown(self):
        text = '-----step6:恢复参数;expect:恢复成功-----'
        self.logger.info(text)
        collector_current = self.common.show_param(self.collector)
        if collector_current != self.collector_default:
            self.primary_sh.execute_gsguc(
                'set', self.constant.GSGUC_SUCCESS_MSG,
                f'{self.collector}={self.collector_default}')
            restart_res = self.primary_sh.restart_db_cluster()
            self.logger.info(restart_res)
        show_collector = self.common.show_param(self.collector)

        log_min_msg_current = self.common.show_param(self.log_min_msg)
        if log_min_msg_current != self.log_min_msg_default:
            self.primary_sh.execute_gsguc(
                'reload', self.constant.GSGUC_SUCCESS_MSG,
                f'{self.log_min_msg}=\'{self.log_min_msg_default}\'')
        show_log_min_msg = self.common.show_param(self.log_min_msg)

        log_dir_current = self.common.show_param(self.log_dir)
        if log_dir_current != self.log_dir_default:
            self.primary_sh.execute_gsguc(
                'reload', self.constant.GSGUC_SUCCESS_MSG,
                f'{self.log_dir}=\'{self.log_dir_default}\'')
        show_log_dir = self.common.show_param(self.log_dir)

        debug_plan_current = self.common.show_param(self.debug_plan)
        if debug_plan_current != self.debug_plan_default:
            self.primary_sh.execute_gsguc(
                'reload', self.constant.GSGUC_SUCCESS_MSG,
                f'{self.debug_plan}=\'{self.debug_plan_default}\'')
        show_debug_plan = self.common.show_param(self.debug_plan)

        text_remove = '-----step7:清理残留日志文件;expect:清理成功-----'
        remove_cmd = f"rm -rf {self.dir_new}"
        remove_result = self.primary_node.sh(remove_cmd).result()
        self.logger.info(remove_result)
        remove_test_cmd = f"ls {self.dir_new}"
        remove_test_log = self.primary_node.sh(remove_test_cmd).result()
        self.logger.info(remove_test_log)

        self.logger.info('-----断言tearDown-----')
        self.assertEquals(show_collector, self.collector_default,
                          '执行失败' + text)
        self.assertEquals(show_log_min_msg, self.log_min_msg_default,
                          '执行失败' + text)
        self.assertEquals(show_log_dir, self.log_dir_default,
                          '执行失败' + text)
        self.assertEquals(show_debug_plan, self.debug_plan_default,
                          '执行失败' + text)
        self.assertIn("No such file or directory", remove_test_log, '执行失败:' + text_remove)
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
